package com.task.mall.filter;

import com.google.gson.Gson;
import com.task.mall.bean.Result;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/api/admin/*")
public class AdminFilter implements Filter {
    Gson gson = new Gson();
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        //获取当前请求方法
        String method = request.getMethod();
        //获取当前请求的URI路径
        String requestURI = request.getRequestURI();
        // System.out.println(request.getMethod() + " -- " + request.getRequestURI() + " -- " + request.getSession().getId());
        response.setHeader("Access-Control-Allow-Origin","http://localhost:8080");
        response.setHeader("Access-Control-Allow-Methods","POST,GET,OPTIONS,PUT,DELETE");
        response.setHeader("Access-Control-Allow-Headers","x-requested-with,Authorization,Content-Type");
        response.setHeader("Access-Control-Allow-Credentials","true");

        // 进行判断后放行
        if (!method.equalsIgnoreCase("OPTIONS")){
            // 不是options请求，需要判断是否加权限
            if (auth(requestURI)){
                // 是否需要权限 -- /api/admin/admin/allAdmins
                String email = (String) request.getSession().getAttribute("email");
                if (email == null){
                    //表示当前请求需要权限，但是此时session中没有东西
                    Result res = new Result();
                    res.setCode(10000);
                    res.setMessage("当前请求需要登录后才可以使用哦！");
                    response.getWriter().println(gson.toJson(res));
                    return;
                }
            }
        }
        chain.doFilter(request, response);
    }

    /**
     * 是否需要权限
     * @param requestURI
     * @return
     */
    private boolean auth(String requestURI) {
        if ("/api/admin/admin/login".equalsIgnoreCase(requestURI)){
            return false;
        }else if ("/api/admin/admin/logoutAdmin".equalsIgnoreCase(requestURI)){
            return false;
        }
        return true;
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
